import pymysql

class Database:
    # 构造函数
    port = 3306
    charset = "utf8"
    def __init__(self, host="127.0.0.1", user="root", passwd=None, database=None) -> None:
        # 将构造函数参数转换为实例属性
        self.host = host
        self.user = user
        self.passwd = passwd
        self.database = database
        # 获取mysql的连接以及游标对象
        self.conn = conn = pymysql.connect(
            host=self.host, user=self.user,passwd=self.passwd,database=self.database,port=self.port,charset=self.charset
        )
        self.cursor = conn.cursor()

    def create(self,sql,condition=None):
        try:
            if condition and len(condition) == 1:
                result = self.cursor.execute(sql, condition)
            else:
                result = self.cursor.executemany(sql, condition)
            self.conn.commit()
            print(f"成功插入{result}行数据")
        except Exception:
            self.conn.rollback()
            print("插入错误，数据回滚")
        

    def read(self,sql, condition=None, data_lines=None):
        result = self.cursor.execute(sql, condition)
        if not data_lines:
            data = self.cursor.fetchall()
        else:
            data = self.cursor.fetchmany(data_lines)
        print(f"查询出{result}行数据")
        for k in data:
            print(*k)


    def update(self,sql, condition=None):
        try:
            result = self.cursor.execute(sql, condition)
            self.conn.commit()
            print(f"成功更新{result}行数据")
        except Exception:
            self.conn.rollback()
            print("更新错误，数据回滚")

    def delete(self,sql, condition=None):
        try:
            result = self.cursor.execute(sql, condition)
            self.conn.commit()
            print(f"成功删除{result}行数据")
        except Exception:
            self.conn.rollback()
            print("删除错误，数据回滚")
"""
if __name__ == "__main__":
    db = Database(passwd="123456", database="python")
  
    insert = '''
insert into user(id,name,age,gender)
values(%s, %s, %s, %s)

    db.create(sql=insert, condition=((2,"小花",22,"女"),(3,"小李",15,"女")))
  
        select = '''
        select * from user where id < %s
   
        db.read(sql=select, condition=3)
   

   
    update = '''
        update user set name="老刘" where name=%s
  
    db.update(sql=update, condition="小花")
   
 
    delete = '''
        delete from user where id = %s

    db.delete(sql=delete, condition=3)
 """
if __name__ == "__main__":
    db = Database(passwd="123456", database="python")

    insert = '''
    INSERT INTO user(id, name, age, gender)
    VALUES(%s, %s, %s, %s)
    '''
    db.create(sql=insert, condition=[(2, "小花", 22, "女"), (3, "小李", 15, "女")])

    select = '''
    SELECT * FROM user WHERE id < %s
    '''
    db.read(sql=select, condition=(3,))

    update = '''
    UPDATE user SET name="老刘" WHERE name=%s
    '''
    db.update(sql=update, condition=("小花",))

    delete = '''
    DELETE FROM user WHERE id = %s
    '''
    db.delete(sql=delete, condition=(3,))